﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using Newtonsoft.Json;



namespace dc_power_monitor.userControl
{
    public partial class home_uc : UserControl
    {

        private recordHelper rec;


        public delegate void sendModbusHold(ushort add, ushort value);
        public sendModbusHold sendHold;

        public delegate void sendModbusCoil(ushort add, bool value);
        public sendModbusCoil sendCoil;

        private RootObject param;
        // private int timeFlag;
        private bool faultSta;
        private int ctrmodFlag;
        private int volmodFlag;

        private string[] fault_str = {
            "输出过压锁死 ",
            "短路锁死 ",
            "内部过温 ",
            "PFC故障 ",
            "风扇故障 ",
            "内部通信异常 ",
            "输出继电器故障 ",
            "放电电路故障 ",
        };
        private string[] protect_h_str = {
            "内部继电器电路异常保护 ",
            "输出电容电压不平衡 ",
            "输出电容过压 ",
        };

        private string[] protect_l_str = {
            "输入停电 ",
            "输入欠压 ",
            "输入过压 ",
            "交流不平衡 ",
            "交流缺相 ",
            "环温过温关机 ",
            "环温低温关机 ",
            "与监控通信失败关机 ",
            "硬地址冲突 ",
            "硬件地址异常 ",
            "未插接到位 ",
            "序列号重复 ",
            "PFC母线不平衡 ",
            "PFC母线电压过欠压 ",
            "放电电路异常 ",
            "输出异常 ",

        };
        public home_uc()
        {
            InitializeComponent();
            timerTest.Start();
            faultSta = true;
            //timeFlag = 0;
            param = new RootObject();
            rec = new recordHelper("log_opreat_fault.db");
            int num = trcVolSet.Value;
            int set_vol = 100000 / 1000 * num;
            txtVolSetting.Text = (set_vol / 100).ToString() ;
            txtCurSetting.Text = "80";

        }
        private delegate void SetTextCallBack(string text, Label lab);
        private void SetText(SetTextCallBack func, string text , Label lab)
        {
            if (lab.InvokeRequired)
            {

                lab.Invoke(func, new object[] { text ,lab});
            }
            else
            {
                func(text , lab);
            }
        }

        private void LoadData(string txt, Label lab)
        {
            lab.Text = txt;
        }

        private delegate void SetTextCallBack_box(string text, TextBox lab);
        private void SetTextBox(SetTextCallBack_box func, string text, TextBox lab)
        {
            if (lab.InvokeRequired)
            {

                lab.Invoke(func, new object[] { text, lab });
            }
            else
            {
                func(text, lab);
            }
        }

        private void LoadData_box(string txt, TextBox lab)
        {
            lab.Text = txt;
        }



        private delegate void SetChartCallBack(int v, int c);
        private void SetChartText(SetChartCallBack func, int v, int c)
        {
           /* if (chart1.InvokeRequired)
            {

                chart1.Invoke(func, new object[] { v,c});
            }
            else
            {
                func(v,c);
            }*/
        }

        private void setChart(int v, int c)
        {
            /*chart1.ChartAreas[0].AxisX.Maximum = timeFlag + 10;
            chart1.ChartAreas[0].AxisX.ScaleView.Scroll(chart1.ChartAreas[0].AxisX.Maximum);


            chart1.Series["Voltage"].Points.AddXY(timeFlag, v);
            chart1.Series["Curent"].Points.AddXY(timeFlag, c);
            timeFlag++;*/
        }

        private string intString2FloatString(string str, string unit)
        {
            int ret = Convert.ToInt32(str);

            return (ret / 10).ToString() + "." + (ret % 10).ToString() + unit;
        }

        private string intString2FloatString2(string str, string unit)
        {
            int ret = Convert.ToInt32(str);

            return (ret / 100).ToString() + "." + (ret % 100).ToString() + unit;
        }
        /// <summary>
        /// 更新home_uc类的param数据
        /// </summary>
        /// <param name="pp"></param>
        public void RecieveData(RootObject pp)
        {
            param = pp;

            //if(param.vSet != "0" || param.cSet != "0")
            //{
            //    SetTextBox(LoadData_box, param.vSet, txtVolSetting);
            //    SetTextBox(LoadData_box, param.cSet, txtCurSetting);
            //}
            
        }

        
        private void chart1_Click(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 显示param数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerTest_Tick(object sender, EventArgs e)
        {
            
            SetText(LoadData, intString2FloatString(param.vol, null), labVol);
            SetText(LoadData, intString2FloatString(param.cur, null), labCur);
            SetText(LoadData, intString2FloatString2(param.pow, null), labPow);


            if (param.ctrmod == false)
            {
                SetText(LoadData, "本地", labCtrMode);
                SetTextBox(LoadData_box, param.vSet, txtVolSetting);
                SetTextBox(LoadData_box, param.cSet, txtCurSetting);
                ctrmodFlag = 0;
            }
            else if (param.ctrmod == true)
            {
                SetText(LoadData, "远程", labCtrMode);
                if(ctrmodFlag == 0)
                {
                    SetTextBox(LoadData_box, param.vSet, txtVolSetting);
                    SetTextBox(LoadData_box, param.cSet, txtCurSetting);
                }
                ctrmodFlag = 1;
            }
            //SetText(LoadData, intString2FloatString(param.inPow, " kW"), labInP);
            //SetText(LoadData, intString2FloatString(param.inCur, " A"), labInCur);
            //SetText(LoadData, intString2FloatString(param.inHz, " Hz"), labInHz);
            //SetText(LoadData, intString2FloatString(param.inUV, " V"), labInUV);
            //SetText(LoadData, intString2FloatString(param.inVW, " V"), labInVW);
            //SetText(LoadData, intString2FloatString(param.inWU, " V"), labInWU);
            //SetText(LoadData, intString2FloatString(param.EFF, "%"), labEff);

            if(param.devsta != null)
            {
                if (param.devsta[0] == true)
                {
                    if (param.sta == true)
                    {
                        SetText(LoadData, "运行中", labDevSta);
                    }
                    else if (param.sta == false)
                    {
                        SetText(LoadData, "待机", labDevSta);
                    }
                    faultSta = true;
                }
                else
                {
                    string name = "";
                    string str = "";
                    string code = "";

                    if (param.devsta[1] == true)
                        str = "防雷故障";
                    if (param.devsta[2] == false)
                        str = "继电器故障";
                    if (param.devsta[3] == true)
                    {
                        str = "模块故障 ";
                        for (int i = 0; i < fault_str.Length; i++)
                        { 
                            if(param.errcode[0] >> i == 1)
                            {
                                name += fault_str[i];
                            }
                        }
                        for (int i = 0; i < protect_h_str.Length; i++)
                        {
                            if (param.errcode[1] >> i == 1)
                            {
                                name += protect_h_str[i];
                            }
                        }
                        for (int i = 0; i < protect_l_str.Length; i++)
                        {
                            if (param.errcode[2] >> i == 1)
                            {
                                name += protect_l_str[i];
                            }
                        }
                        code = "故障状态码 " + param.errcode[0].ToString("x") + "保护状态码" + (param.errcode[1] * 0x10000 + param.errcode[2]).ToString("x");
                    }
                        
                    if(param.dissta == true)
                    {
                        str = "放电异常";
                    }
                    SetText(LoadData, str, labDevSta);
                    if (faultSta == true)
                    {
                        faultSta = false;
                        rec.addFaultRecord(str + name + code);
                    }
                }
            }
            


            if (param.volmod == false)
            {
                SetText(LoadData, "高压模式", labVolMod);
                volmodFlag = 0;
            }
            else
            {
                SetText(LoadData, "低压模式", labVolMod);
                volmodFlag = 1;
            }

            //SetText(LoadData, param.mNum, labModuleNum);
            //SetText(LoadData, intString2FloatString(param.interTem, " ℃"), labInterTemp);
            //SetText(LoadData, intString2FloatString(param.inletTem, " ℃"), labInlet);

            int v = Convert.ToInt32(param.vol) / 10;
            int c = Convert.ToInt32(param.cur) / 10;



            SetChartText(setChart, v, c);
        }

        private void btnSwitch_Click(object sender, EventArgs e)
        {
            
        }

        private void txtVolSetting_TextChanged(object sender, EventArgs e)
        {

        }

        private void txtVolSetting_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (param.ctrmod == false)
            {
                MessageBox.Show("当前为本地模式，远程无法设置，若需要更改模式请在设置里选择！");
                return;
            }
            e.Handled = true;
            if ((e.KeyChar >= '0' && e.KeyChar <= '9')  || e.KeyChar == 8)
            {
                e.Handled = false;
            }
        }

        private void txtCurSetting_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (param.ctrmod == false)
            {
                MessageBox.Show("当前为本地模式，远程无法设置，若需要更改模式请在设置里选择！");
                return;
            }
            e.Handled = true;
            if ((e.KeyChar >= '0' && e.KeyChar <= '9') || e.KeyChar == 8)
            {
                e.Handled = false;
            }

            
        }

        private void metroTrackBar1_Scroll(object sender, ScrollEventArgs e)
        {
            
        }

        

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            string opreat = "设置输出电压：" + txtVolSetting.Text + "V,  输出电流：" + txtCurSetting.Text + "A";
            rec.addOpreatRecord(ConfigurationManager.AppSettings["user"], opreat);


            ushort v = Convert.ToUInt16(txtVolSetting.Text);
            ushort i = Convert.ToUInt16(txtCurSetting.Text);

            

            this.check_control_mod_send_coil(0x03, true);

            this.check_control_mod_send_hold(0x11, v);
            this.check_control_mod_send_hold(0x12, i);
        }

        private void trcVolSet_Scroll(object sender, EventArgs e)
        {
            if(param.ctrmod == false)
            {
                MessageBox.Show("当前为本地模式，远程无法设置，若需要更改模式请在设置里选择！");
                return;
            }
            int num = trcVolSet.Value;
            int set_vol = 100000 / 1000 * num;
            txtVolSetting.Text = (set_vol / 100).ToString() ;
        }

        private void chart1_Click_1(object sender, EventArgs e)
        {

        }

        private void label21_Click(object sender, EventArgs e)
        {

        }

        private void btnSetting1_Click(object sender, EventArgs e)
        {
            string vol_cur = ConfigurationManager.AppSettings["set1"];
            string[] volCur = vol_cur.Split(' ');

            txtVolSetting.Text = volCur[0];
            txtCurSetting.Text = volCur[1];
        }

        private void btnSetting2_Click(object sender, EventArgs e)
        {
            string vol_cur = ConfigurationManager.AppSettings["set2"];
            string[] volCur = vol_cur.Split(' ');

            txtVolSetting.Text = volCur[0];
            txtCurSetting.Text = volCur[1];
        }

        private void btnSetting3_Click(object sender, EventArgs e)
        {
            string vol_cur = ConfigurationManager.AppSettings["set3"];
            string[] volCur = vol_cur.Split(' ');

            txtVolSetting.Text = volCur[0];
            txtCurSetting.Text = volCur[1];
        }

        private void btnSetting4_Click(object sender, EventArgs e)
        {
            string vol_cur = ConfigurationManager.AppSettings["set4"];
            string[] volCur = vol_cur.Split(' ');

            txtVolSetting.Text = volCur[0];
            txtCurSetting.Text = volCur[1];
        }

        private void btnSetting5_Click(object sender, EventArgs e)
        {
            string vol_cur = ConfigurationManager.AppSettings["set5"];
            string[] volCur = vol_cur.Split(' ');

            txtVolSetting.Text = volCur[0];
            txtCurSetting.Text = volCur[1];
        }

        private void home_uc_Load(object sender, EventArgs e)
        {

        }

        private void labInHz_Click(object sender, EventArgs e)
        {

        }

        private void txtAlarm_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            rec.addOpreatRecord(ConfigurationManager.AppSettings["user"], "开机");

            ushort v = Convert.ToUInt16(txtVolSetting.Text);
            ushort i = Convert.ToUInt16(txtCurSetting.Text);
 
            if (v > 500 && volmodFlag == 1)
            {
                MessageBox.Show("当前为低压模式，输出电压最高500v，如需输出更高电压请在设置界面更改电压模式！");
                return;
            }

            this.check_control_mod_send_coil(0x03, true);
            this.check_control_mod_send_hold(0x11, v);
            this.check_control_mod_send_hold(0x12, i);

            this.check_control_mod_send_coil(0x01, true);

        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            rec.addOpreatRecord(ConfigurationManager.AppSettings["user"], "关机");

            powerOnOff result = new powerOnOff();

            result.cmd = "3";

            result.sw = "0";

            string jsonStr = JsonConvert.SerializeObject(result);

            this.check_control_mod_send_coil(0x01, false);
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void txtCurSetting_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (param.volmod == false && Convert.ToInt32(txtCurSetting.Text) > 80)
                {
                    txtCurSetting.Text = "80";
                }
            }
            catch
            {

            }
            
        }

        private void check_control_mod_send_hold(ushort add, ushort value)
        {
            if(ctrmodFlag == 1)
                sendHold.BeginInvoke(add, value, null, null);
            if (ctrmodFlag == 0)
            {
                MessageBox.Show("设备为本地模式，不响应远程控制，请设置里切换控制模式！");
            }
        }

        private void check_control_mod_send_coil(ushort add, bool value)
        {
            if (ctrmodFlag == 1)
                sendCoil.BeginInvoke(add, value, null, null);
            if (ctrmodFlag == 0)
            {
                MessageBox.Show("设备为本地模式，不响应远程控制，请设置里切换控制模式！");
            }
        }

        private void labPow_Click(object sender, EventArgs e)
        {

        }
    }
}
